import { useEffect, useState } from "react";

function Son() {
  useEffect(() => {
    // 组件挂载时开启定时器
    console.log("Son组件被挂载了");
    let timer = setInterval(() => {
      console.log("Son组件定时器执行了");
    }, 1000);
    // 组件卸载时关闭定时器
    return () => {
      clearInterval(timer);
      console.log("Son组件被卸载了");
    };
  }, []);
  return <div>this is son</div>;
}

function App() {
  // 通过条件渲染模拟组件卸载
  const [show, setShow] = useState(true);
  return (
    <>
      {show && <Son />}
      {/* 控制子组件的挂载与卸载 */}
      <button onClick={() => setShow(!show)}>
        {show ? "卸载" : "挂载"}Son组件
      </button>
    </>
  );
}

export default App;
